int[] data = new int[10];
data
? 10data
? 0, 1, 2, ..., 8, 9Recall that:
The length of an array is how many slots it has. An array of length N has slots indexed 0..(N-1)
Indexes must be an integer type.
It is OK to have spaces around the index of an array,
for example data[1]
data[ 1 ]
Say that an array were declared:
int[] data = new int[10];
Here are some subscripted variables of this array:
data[ -1 ] | always illegal |
data[ 10 ] | illegal (given the above declaration) |
data[ 1.5 ] | always illegal |
data[ 0 ] | always OK |
data[ 9 ] | OK (given the above declaration) |
If your program contains an expression that is always illegal, it will not compile. But often the size of an array is not known to the compiler. The size of an array often is determined by data at run time. Since the array is constructed as the program is running, the compiler does not know its length and can't predict some errors. If, when it is running, the program refers to a slot that does not exist, an exception is thrown, and (usually) the program is terminated.
As a Java program is running, each time an array index is used it is checked to be sure that it is OK. This is called bounds checking, and is extremely important for catching errors.